const service = require('../groupBuyService.js');
const utilService = require('../../../../utils/utilService.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   * goodsIdstring商品id
    goodsUrlstring商品图片
    numberinteger剩余开团人数
    totalinteger开团总人数
    successNuminteger已经成功开团数量
    worthinteger团价值
    secondinteger剩余时间
    playMethodstring拼团玩法
    rulestring拼团规则
    userCommentsarray评论
    grouperstring团长
   */
  data: {
    //轮播图参数
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    timeCounting: false,//倒计时中
    productUrls: [],
    userSweets: 0,
    integral :222,
    goodsName:"NAN",
    goodsId: '',
    groupBuyId:"",
    type:'新人团',
    logo:"",
    logoName:"",
    isNew:true,
    worth: 0,
    numbers: 25,
    successNum: 34,
    total: 23,
    number:1,
    playMethod: "",
    grouper: "",
    groupBuyUserId:"",
    countDownDay: 0,
    countDownHour: 0,
    countDownMinute: 0,
    countDownSecond: 0,
    isJoin: false,
    status: 0,//拼团状态 团长  0 进行中 1 失败 2成功  非团长 4 未参团  3已参团
    isGrouper: 1, // 是否是团长 0否 1是
    grouperId:"",
    videoUrl: '', //播放视频地址
    goodsUrl: "",
    shareMsg:"",//分享信息
    groupCount: 0,//拼团数量
    goodsDetailType: 0,
    rule: '1.提前挑选 \n 2.商品 \n 3.每天',
    nodes: [{
      name: 'div',
      attrs: {
        class: 'div_class',
        style: 'line-height: 60px; color: #353535;'
      },
      children: [{
        type: 'text',
        text: '1.提前挑选 \n 2.商品 \n 3.每天'
      }]
    }],
    defaultPhoto: '/images/home/default_head.png',
    userUrls: [],
    products:[],
    starPage: 0,
    myOptions: null

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('-----++++++++0--------',options["gBId"],options["gBUId"])
    this.setData({
      myOptions: options
    })
    var self = this;
    self.authAlert = self.selectComponent("#authAlert");
    self.authAlert.bindCatch()
    app.loginPromise.then(() => {
      self.moreList = this.selectComponent("#more-list");
      self.loadData(options, function () {
      })
    });
  },
  authSuccess() {
    this.moreList = this.selectComponent("#more-list");
    var options = this.data.myOptions
    this.loadData(options, function () {
    });
  },

  loadData: function (options, complate){
    var self = this;
    self.getShareMessage(5);
    let inviteUserId = options["uId"] == undefined ? options["userId"] : options["uId"];
    let groupBuyId = options["gBId"];
    let groupBuyUserId = options["gBUId"];
    self.setData({
      groupBuyId: groupBuyId,
      groupBuyUserId: groupBuyUserId,
      grouperId: inviteUserId,
      windowHeight: wx.getStorageSync('windowHeight')
    })
    //获取用户多少个果冻
    app.func.Get(true, app.api.get_userInfo, { 'userId': app.globalData.userId }, function (data) {
      app.globalData.userSweets = data.integral
      self.setData({
        userSweets: app.globalData.userSweets
      })
    });
    self.requstGroupbuyDetail(groupBuyId, groupBuyUserId,function(){
      typeof complate == "function" && complate()
    });
    // self.requestMore();
    // 获取video实例
    self.showVideo = self.selectComponent("#showVideo");
  },
  requstGroupbuyDetail: function(groupBuyId, groupBuyUserId,complate){
    var self = this;
    console.log("----------------------------------requstGroupbuyDetail", groupBuyId, groupBuyUserId)
    service.groupbuyDetail(groupBuyId, groupBuyUserId, function (res) {
      console.log("----------------------------------requstGroupbuyDetail", res)
      
      var users = new Array(res.total);
      var strs = res.userUrls;
      users.splice(0, strs.length);
      var users = strs.concat(users);
      users.splice(0, 0, res.grouper);
      var products = res.goodsUrlList;
      if (res.second > 0){
        self.updateTime(res.second);
      }
      self.setData({
        goodsDetailType: res.goodsDetailType,
        integral: res.integral,
        goodsName: res.goodsName,
        goodsId: res.goodsId,
        worth: res.worth,
        groupCount: res.groupCount,
        successNum: res.successNum,
        total: res.total,
        number: res.number,
        userUrls: users,
        // playMethod: res.playMethod,
        // rule: res.rule,
        grouper: res.grouper,
        status: res.status,
        productUrls: products,
        isGrouper: res.isGrouper,
        groupBuyUserId: res.groupBuyUserId,
        goodsUrl: res.goodsUrl,
        grouperId: res.grouperId
        // logo: res.logo,
        // logoName: res.logoName
      })
      typeof complate == "function" && complate()
    });
  },

  playVideo: function (e) {
    let videoUrl = this.data.productUrls[e.currentTarget.dataset.index].video;
    this.setData({
      videoUrl: videoUrl
    });
    this.showVideo.show()
  },
  /**
   * 视频取消回调
   */
  videoViewDimiss: function () {
    this.setData({
      isStartVisible: false,
    })
  },
  /**
   * view触底监听
   */
  onReachBottom: function () {
    this.moreList.reachBottom()
    this.setData({
      starPage: this.data.starPage+1
    })
    // this.requestMore()
  },
  submit:function(e){
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 7);
    console.log("formId-7",e, formId)
  },
  //参团
  join: function(e){
    var self = this;
    service.groupbuyJoin(this.data.grouperId, this.data.groupBuyId, this.data.groupBuyUserId, function (res) {
      console.log(res);
      self.requstGroupbuyDetail(self.data.groupBuyId, self.data.groupBuyUserId, function () {
      });
      if (res.message != null || res.message != undefined) {
        wx.showToast({
          title: res.message,
          icon: "none"
        })
      } else{
        wx.showToast({
          title: "参团成功",
          icon:"none"
        })
      }
    },function(error){
        wx.showToast({
          title: error.data.message,
          icon: "none"
        })
    })
  },
  //开团
  open: function (e) {
    wx.navigateTo({
      url: '/redPacket/pages/groupBuy/groupBuyGoodsDetail/groupBuyGoodsDetail?gBId=' + this.data.groupBuyId + "&goodsId=" + this.data.goodsId,
    })
  },
  //订单详情
  checkDetails: function (e) {
    //1 红包 0 实物
    if (this.data.goodsDetailType == 1){
      // 跳支付成功页面
      var param = {};
      param["saleTypeId"] = 2;
      param["goodsId"] = this.data.goodsId;
      // 跳支付成功页面
      wx.navigateTo({
        url: "../../../../pages/common/paySuccess/paySuccess?result=1&type=1" + "&goodsData=" + JSON.stringify(param)
      })
    }else{
      wx.navigateTo({
        url: '/mineSubs/pages/getBaby/getBaby?type=1',
      })
    }
 
  },
  //海报分享
  shareImage: function (e) {
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId,30);
    let param = new Object();
    let goodUrl = this.data.goodsUrl;
    let pagePath = 'redPacket/pages/groupBuy/gBDetail/gBDetail?gBId=' + this.data.groupBuyId + "&gBUId=" + this.data.groupBuyUserId + '&uId=' + getApp().globalData.userId;
    let groupCount = this.data.successNum;
    let goodName = this.data.goodsName;
    let goodsTotal = this.data.groupCount;

    param['goodUrl'] = goodUrl;
    param['pagePath'] = encodeURIComponent(pagePath);
    param['groupCount'] = groupCount;
    param['goodName'] = goodName;
    param['goodsTotal'] = goodsTotal;
    wx.navigateTo({
      url: '../../../../pages/goodsShare/goodsShare?group=' + JSON.stringify(param) + '&pageType=1',
    });
  },
  updateTime: function (totalSecond){
    if (this.data.timeCounting == true) {
      return;
    }
    this.setData({
      timeCounting: true,
    })
    var interval = setInterval(function () {
      // 秒数
      var second = totalSecond;
      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        this.setData({
          timeCounting: false,
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
        this.requstGroupbuyDetail(this.data.groupBuyId, this.data.groupBuyUserId, function () {
        })
      }
    }.bind(this), 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  backHome: function(e){
    wx.reLaunch({
      url: '../../../../pages/home/home',
    })
  },
  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
        self.setData({
          shareMsg: data.title
        })
      },
      function (error) {

      }
    );
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    var options = this.data.myOptions
    this.loadData(options, function () {
      wx.stopPullDownRefresh()
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var title = this.data.shareMsg
    title = title.replace(/#/, app.globalData.userInfo.nickName)
    title = title.replace(/{}/, this.data.goodsName)
    var param = '?uId=' + app.globalData.userId + '&gBId=' + this.data.groupBuyId + "&gBUId=" + this.data.groupBuyUserId + "&groupCount=" + this.data.groupCount
    var path = 'redPacket/pages/groupBuy/gBDetail/gBDetail' + param
    return {
      title: title,
      path: path,
      imageUrl: this.data.goodsUrl,
      success: function (res) {
        // 需要在页面onLoad()事件中实现接口
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });
      },
      fail: function (res) {
        console.info(JSON.stringify(res))
      }
    }
  },
  //点击赚花
  earnRedFloweClick: function (e) {
    wx.navigateTo({
      url: '/mineSubs/pages/getFlowers/getFlowers',
    })
  },
})